import java.util.*;

public class Solution2 {
    public int minMutation(String startGene, String endGene, String[] bank) {
        Set<String> check = new HashSet<>(); // 用来标记已经搜索过的状态
        Set<String> hash = new HashSet<>(); // 用来统计基因库里面的字符串
        for(String s : bank) {
            hash.add(s);
        }
        char[] change = {'A', 'C', 'G', 'T'};
        if(startGene.equals(endGene)) {
            return 0;
        }
        if(!hash.contains(endGene)) {
            return -1;
        }

        Queue<String> q = new LinkedList<>();
        q.add(startGene);
        check.add(startGene);
        int step = 0;
        while(!q.isEmpty()) {
            step++;
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                String t = q.poll();
                for(int j = 0; j < 8; j++) {
                    char[] tmp = t.toCharArray();
                    for(int k = 0; k < 4; k++) {
                        tmp[j] = change[k];
                        String next = new String(tmp);
                        if(hash.contains(next) && !check.contains(next)) {
                            q.add(next);
                            check.add(next);
                            if(next.equals(endGene)) {
                                return step;
                            }
                        }
                    }
                }
            }
        }
        return -1;
    }
}
